package com.example.email.service.impl;

import com.example.email.entity.Orders;
import com.example.email.mapper.OrdersMapper;
import com.example.email.service.OrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2023-04-11
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private JavaMailSender mailSender;
    //从配置文件中读取spring.mail.from的值
    @Value("${spring.mail.from}")
    private String from;

    public void send(String to, String subject, String text, List<File> files) {
        //创建邮件
        MimeMessage message = mailSender.createMimeMessage();
        //工具，添加主题，收件人，发件人，附件
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            //邮件从哪个邮箱发出
            helper.setFrom(from);
            //邮件发往哪个邮箱
            helper.setTo(to);
            //主题
            helper.setSubject(subject);
            //邮件内容
            helper.setText(text, true);
            //附件
            if (files.size() != 0) {
                for (File file : files) {
                    //挂附件
                    helper.addAttachment(file.getName(), file);
                }
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        //发邮件
        mailSender.send(message);
    }
}
